import { View, Text, StyleSheet, ScrollView, TouchableOpacity, ActivityIndicator, TextInput, KeyboardAvoidingView, Platform } from 'react-native';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { useState, useEffect } from 'react';
import { communityService } from '../../utils/api/services';
import { TopicResponse, TopicCommentResponse } from '../../utils/api/types';
import { formatDate } from '../../utils/date';
import { MaterialIcons } from '@expo/vector-icons';
import { useAuth } from '../../store/auth/AuthContext';
import { useTheme } from '../../components/theme/ThemeContext';
import Toast from 'react-native-toast-message';

export default function TopicDetailScreen() {
  const router = useRouter();
  const { id } = useLocalSearchParams();
  const { user } = useAuth();
  const { theme } = useTheme();
  const [topic, setTopic] = useState<TopicResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [comments, setComments] = useState<TopicCommentResponse[]>([]);
  const [newComment, setNewComment] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [showCommentInput, setShowCommentInput] = useState(false);

  // 获取话题详情
  useEffect(() => {
    const fetchTopic = async () => {
      try {
        setLoading(true);
        const response = await communityService.getTopic(Number(id));
        console.log('话题详情原始数据:', response);
        if (response?.data) {
          setTopic(response.data);
          console.log('设置的话题数据:', response.data);
        }
      } catch (error) {
        console.error('获取话题详情失败:', error);
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchTopic();
    }
  }, [id]);

  // 获取评论列表
  useEffect(() => {
    const fetchComments = async () => {
      try {
        const response = await communityService.listTopicComments(Number(id));
        console.log('评论列表原始数据:', JSON.stringify(response, null, 2));
        // 检查响应数据结构
        if (response?.code === 200 && Array.isArray(response?.data?.data)) {
          setComments(response.data.data);
          console.log('设置的评论数据:', response.data.data);
        } else {
          setComments([]);
        }
      } catch (error) {
        console.error('获取评论列表失败:', error);
        setComments([]);
      }
    };

    if (id) {
      fetchComments();
    }
  }, [id]);

  // 处理点赞
  const handleLike = async () => {
    if (!topic) return;
    
    try {
      // 发送API请求
      await communityService.likeTopic(topic.id);
      
      // 重新获取最新数据
      const response = await communityService.getTopic(Number(id));
      if (response?.data) {
        setTopic(response.data);
      }
    } catch (error) {
      console.error('点赞操作失败:', error);
    }
  };

  // 处理评论按钮点击
  const handleCommentPress = () => {
    if (!user?.id) {
      Toast.show({
        type: 'error',
        text1: '请先登录',
        text2: '登录后才能发表评论',
      });
      router.push('/user/login');
      return;
    }
    setShowCommentInput(true);
  };

  // 发布评论
  const handleSubmitComment = async () => {
    if (!topic || !newComment.trim()) {
      Toast.show({
        type: 'error',
        text1: '请输入评论内容',
      });
      return;
    }

    if (!user?.id) {
      Toast.show({
        type: 'error',
        text1: '用户未登录',
        text2: '请先登录后再发表评论',
      });
      router.push('/user/login');
      return;
    }

    try {
      setSubmitting(true);
      await communityService.createTopicComment(topic.id, {
        user_id: Number(user.id),
        topic_id: topic.id,
        content: newComment.trim(),
      });

      // 重新获取评论列表
      const response = await communityService.listTopicComments(Number(id));
      if (response?.code === 200 && Array.isArray(response?.data?.data)) {
        setComments(response.data.data);
      }
      
      setNewComment('');
      setShowCommentInput(false);
      
      Toast.show({
        type: 'success',
        text1: '评论发布成功',
      });
    } catch (error) {
      console.error('发布评论失败:', error);
      Toast.show({
        type: 'error',
        text1: '评论发布失败',
        text2: '请稍后重试',
      });
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <View style={[styles.loadingContainer, { backgroundColor: theme.colors.background }]}>
        <ActivityIndicator size="large" color={theme.colors.primary} />
      </View>
    );
  }

  if (!topic) {
    return (
      <View style={[styles.errorContainer, { backgroundColor: theme.colors.background }]}>
        <Text style={[styles.errorText, { color: theme.colors.text }]}>话题不存在或已被删除</Text>
        <TouchableOpacity 
          style={[styles.backButton, { backgroundColor: theme.colors.primary }]}
          onPress={() => router.back()}
        >
          <Text style={styles.backButtonText}>返回上一页</Text>
        </TouchableOpacity>
      </View>
    );
  }

  return (
    <KeyboardAvoidingView 
      style={[styles.container, { backgroundColor: theme.colors.background }]}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <View style={[styles.header, { 
        backgroundColor: theme.colors.card,
        borderBottomColor: theme.colors.border 
      }]}>
        <TouchableOpacity onPress={() => router.back()} style={styles.headerBackButton}>
          <MaterialIcons name="arrow-back" size={24} color={theme.colors.text} />
        </TouchableOpacity>
        <Text style={[styles.headerTitle, { color: theme.colors.text }]}>话题详情</Text>
        <View style={styles.headerRight} />
      </View>

      <ScrollView style={styles.scrollView}>
        <View style={[styles.content, { backgroundColor: theme.colors.card }]}>
          <Text style={[styles.title, { color: theme.colors.text }]}>{topic.title}</Text>
          <View style={styles.metaInfo}>
            <Text style={[styles.date, { color: theme.colors.placeholder }]}>{formatDate(topic.created_at)}</Text>
            <Text style={[styles.author, { color: theme.colors.placeholder }]}>作者ID: {topic.user_id}</Text>
          </View>
          <View style={[styles.divider, { backgroundColor: theme.colors.border }]} />
          <Text style={[styles.text, { color: theme.colors.text }]}>{topic.content}</Text>
        </View>

        <View style={[styles.actions, { 
          backgroundColor: theme.colors.card,
          borderTopColor: theme.colors.border 
        }]}>
          <TouchableOpacity style={styles.actionButton} onPress={handleLike}>
            <MaterialIcons 
              name="thumb-up-off-alt"
              size={20} 
              color={theme.colors.placeholder} 
            />
            <Text style={[styles.actionText, { color: theme.colors.placeholder }]}>
              点赞 ({topic.like_count || 0})
            </Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.actionButton} onPress={handleCommentPress}>
            <MaterialIcons name="chat-bubble-outline" size={20} color={theme.colors.placeholder} />
            <Text style={[styles.actionText, { color: theme.colors.placeholder }]}>
              评论 {comments?.length > 0 ? `(${comments.length})` : ''}
            </Text>
          </TouchableOpacity>
        </View>

        <View style={[styles.commentsSection, { backgroundColor: theme.colors.card }]}>
          <Text style={[styles.commentsTitle, { color: theme.colors.text }]}>评论 ({comments?.length || 0})</Text>
          {Array.isArray(comments) && comments.length > 0 ? (
            comments.map((comment) => (
              <View key={comment.id} style={[styles.commentItem, { backgroundColor: theme.colors.background }]}>
                <View style={styles.commentHeader}>
                  <Text style={[styles.commentAuthor, { color: theme.colors.text }]}>用户ID: {comment.user_id}</Text>
                  <Text style={[styles.commentDate, { color: theme.colors.placeholder }]}>{formatDate(comment.created_at)}</Text>
                </View>
                <Text style={[styles.commentContent, { color: theme.colors.text }]}>{comment.content}</Text>
              </View>
            ))
          ) : (
            <Text style={[styles.noCommentsText, { color: theme.colors.placeholder }]}>暂无评论，快来发表第一条评论吧！</Text>
          )}
        </View>
      </ScrollView>

      {showCommentInput && (
        <View style={[styles.commentInput, { 
          backgroundColor: theme.colors.card,
          borderTopColor: theme.colors.border 
        }]}>
          <TextInput
            style={[styles.input, { 
              backgroundColor: theme.colors.background,
              color: theme.colors.text,
            }]}
            placeholder="写下你的评论..."
            placeholderTextColor={theme.colors.placeholder}
            value={newComment}
            onChangeText={setNewComment}
            multiline
            autoFocus
          />
          <TouchableOpacity
            style={[
              styles.sendButton, 
              (!newComment.trim() || submitting) && styles.sendButtonDisabled,
              { backgroundColor: theme.colors.primary }
            ]}
            onPress={handleSubmitComment}
            disabled={!newComment.trim() || submitting}
          >
            <MaterialIcons name="send" size={20} color="#fff" />
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.closeButton}
            onPress={() => {
              setShowCommentInput(false);
              setNewComment('');
            }}
          >
            <MaterialIcons name="close" size={20} color={theme.colors.placeholder} />
          </TouchableOpacity>
        </View>
      )}
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    backgroundColor: '#fff',
  },
  headerBackButton: {
    padding: 4,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
  },
  headerRight: {
    width: 32,
  },
  scrollView: {
    flex: 1,
  },
  content: {
    padding: 16,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 12,
  },
  metaInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  date: {
    fontSize: 14,
    color: '#666',
    marginRight: 12,
  },
  author: {
    fontSize: 14,
    color: '#666',
  },
  divider: {
    height: 1,
    backgroundColor: '#eee',
    marginVertical: 16,
  },
  text: {
    fontSize: 16,
    lineHeight: 24,
    color: '#333',
  },
  actions: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    padding: 16,
    borderTopWidth: 1,
    borderTopColor: '#eee',
    backgroundColor: '#fff',
  },
  actionButton: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 8,
  },
  actionText: {
    marginLeft: 4,
    fontSize: 14,
    color: '#666',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
    padding: 16,
  },
  errorText: {
    fontSize: 16,
    color: '#666',
    marginBottom: 16,
    textAlign: 'center',
  },
  backButton: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
  },
  backButtonText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '500',
  },
  commentsSection: {
    padding: 16,
    backgroundColor: '#fff',
  },
  commentsTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 16,
    color: '#333',
  },
  commentItem: {
    marginBottom: 16,
    padding: 12,
    backgroundColor: '#f8f8f8',
    borderRadius: 8,
  },
  commentHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 8,
  },
  commentAuthor: {
    fontSize: 14,
    color: '#666',
  },
  commentDate: {
    fontSize: 12,
    color: '#999',
  },
  commentContent: {
    fontSize: 14,
    color: '#333',
    lineHeight: 20,
  },
  commentInput: {
    flexDirection: 'row',
    padding: 12,
    borderTopWidth: 1,
    borderTopColor: '#eee',
    backgroundColor: '#fff',
    alignItems: 'center',
  },
  input: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    borderRadius: 20,
    paddingHorizontal: 16,
    paddingVertical: 8,
    marginRight: 8,
    fontSize: 14,
    maxHeight: 100,
  },
  sendButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: '#007AFF',
    justifyContent: 'center',
    alignItems: 'center',
  },
  sendButtonDisabled: {
    backgroundColor: '#ccc',
  },
  noCommentsText: {
    fontSize: 14,
    color: '#666',
    textAlign: 'center',
    marginTop: 16,
  },
  closeButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 8,
  },
}); 